package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Tag(name = "菜品管理")
@Validated
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO
     * @return
     */
    @PostMapping
    @Operation(summary = "新增菜品")
    public Result<String> save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        Integer result = dishService.save(dishDTO);
        // 清除缓存数据
        cleanCache("sky-take-out:dishCategory:"+dishDTO.getCategoryId());
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error(MessageConstant.ADD_FAILED);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "菜品分页查询")
    public Result<PageResult<DishVO>> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询：{}", dishPageQueryDTO);
        PageResult<DishVO> pageResult = dishService.pageDish(dishPageQueryDTO);
        if (ObjectUtils.isNotEmpty(pageResult)) {
            return Result.success(pageResult);
        } else {
            return Result.error(MessageConstant.NOT_FOUND_QUERY);
        }
    }

    /**
     * 菜品起售、停售
     *
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @Operation(summary = "菜品起售、停售")
    public Result<String> status(@PathVariable Integer status, Long id) {
        log.info("菜品起售、停售：{}", status);
        Integer result = dishService.startOrStop(status, id);
        // 清除缓存数据
        cleanCache("sky-take-out:dishCategory:*");
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error(MessageConstant.UPDATE_STATUS_FAILED);
        }
    }

    /**
     * 根据分类id或菜品名称查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "根据分类id查询菜品")
    public Result<List<Dish>> list(@RequestParam(required = false) Long categoryId,
                                   @RequestParam(required = false) String name) {
        log.info("id：{},name：{}", categoryId,name);
        List<Dish> dishVOList = categoryService.selectByCategoryIdAndName(categoryId,name);
        if (CollectionUtils.isNotEmpty(dishVOList)){
            return Result.success(dishVOList);
        }else {
            return Result.error(MessageConstant.CATEGORY_UNDER_NODISHES);
        }
    }


    /**
     * 根据菜品id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据菜品id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("根据菜品id查询菜品：{}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        if (ObjectUtils.isNotEmpty(dishVO)){
            return Result.success(dishVO);
        }else {
            return Result.error(MessageConstant.NOT_FOUND_QUERY);
        }
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @Operation(summary = "批量删除菜品")
    public Result<String> delete(@RequestParam @NotNull(message = "菜品id不能为空") List<Long> ids) {
        log.info("批量删除菜品：{}", ids);
        boolean flag = dishService.removeByDishIds(ids);
        // 清除缓存数据
        cleanCache("sky-take-out:dishCategory:*");
        if (flag){
            return Result.success();
        }else {
            return Result.error(MessageConstant.DELETE_FAILED);
        }

    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    @Operation(summary = "修改菜品")
    public Result<String> update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        dishService.update(dishDTO);
        // 清除缓存数据
        cleanCache("sky-take-out:dishCategory:*");
        return Result.success();

    }

    /**
     * 清除缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set<String> keys = stringRedisTemplate.keys(pattern);
        if (CollectionUtils.isNotEmpty(keys)){
            stringRedisTemplate.delete(keys);
        }
    }


}
